package com.qf.servlet;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.qf.config.AlipayConfig;
import com.qf.pojo.*;
import com.qf.service.OrderService;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.UUIDUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;

/**
 * 订单后台接口地址
 */
@WebServlet("/order")
public class OrderServlet extends BaseServlet {


    /**
     * 生成订单
     * @param request 请求对象
     * @param response 响应对象
     */
    public void addOrder(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入生成订单的方法中了...");
        //这个用户如果没有登录过,应该让他先登录
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            //没有登录过,请求转发到jsp/login.jsp
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return; //结束了
        }

        //用户登录过

        //封装订单Order
        Order order = new Order() ;
        //UUID生成
        order.setOid(UUIDUtils.getId()) ;
        //下订单时间
        //创建当前日期对象---->java.util.Date
        // 里面有个成员方法:public Instant toInstant() 转换成当前系统时间线
        // --->LocalDateTime
        //public static LocalDateTime ofInstant(Instant instant, ZoneId zone)
        //参数1:系统日期时间
        //参数2:时区  ---使用ZoneId(时区ID)获取当前系统默认时区public static ZoneId systemDefault()
        Date date = new Date() ;
        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        order.setOrdertime(localDateTime);

        //从sesison获取购物车---->Cart----->获取购物车项
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        //封装订单的总金额
        order.setTotal(cart.getTotalMoney());

        //,addres,name,telephone (先写死)

        //获取所有的购物车项的数据
        for(CartItem cartItem:  cart.getItems()){
            //封装订单项OrderItem实体  ---->里面商品的数量/商品实体/小计金额---->来自购物车项
            OrderItem orderItem = new OrderItem() ;
            orderItem.setItemid(UUIDUtils.getId());
            orderItem.setCount(cartItem.getCount());
            orderItem.setProduct(cartItem.getProduct()) ;
            orderItem.setSubtotal(cartItem.getSubTotal()) ;

            //这个订单项属于哪个订单的
            orderItem.setOrder(order);

            //订单项封装多个订单项
            order.getItems().add(orderItem) ;

        }

        //订单属于哪个用户的
        order.setUser(user);
        //调用OrderService
        OrderService orderService = new OrderServiceImpl() ;
        orderService.addOrder(order);//插入订单数据


        //将订单实体存储在Request域中
        request.setAttribute("bean",order) ;

        //请求转发到订单详情页面中之前,应该session域中存储到cart删除掉
        request.getSession().removeAttribute("cart");
        request.getRequestDispatcher("/jsp/order_info.jsp").forward(request,response);


    }


    //我的订单列表---分页查询

    //支付订单
    public void pay(HttpServletRequest request,HttpServletResponse response){
        System.out.println("订单支付进来了...");
        //获取订单编号
        //收货人
        //电话...
        String oid = request.getParameter("oid");
        String address = request.getParameter("address");
        String name = request.getParameter("name");

        String telephone = request.getParameter("telephone");


        //封装订单
        Order order = new Order() ;
        order.setName(name);
        order.setAddress(address);
        order.setTelephone(telephone);

        //调用业务接口更新订单中的用户信息
        OrderService orderService = new OrderServiceImpl() ;

        orderService.updateOrder(order) ;


        //支付宝的客户端的配置
        try {



            //获得初始化的AlipayClient
            //获取当前config包下的AlipayConfig的参数
            AlipayClient alipayClient = new DefaultAlipayClient(
                    AlipayConfig.gatewayUrl,
                    AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key,
                    "json",
                    AlipayConfig.charset, AlipayConfig.alipay_public_key,
                    AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

           // String orderNO = request.getParameter("oid");
            //调用业务层接口
            //通过订单编号获取订单
            Order orderObj = orderService.getOrderById(oid);


            //			商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no =  orderObj.getOid() ;
//			//付款金额，必填
            Double total = orderObj.getTotal();
            String total_amount = String.valueOf(total) ;

//			//订单名称，必填
            String subject = "商品支付";

            //商品描述，可空
            String body = "欢迎使用支付宝支付";



            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\""
                    + total_amount + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //        + "\"total_amount\":\""+ total_amount +"\","
            //        + "\"subject\":\""+ subject +"\","
            //        + "\"body\":\""+ body +"\","
            //        + "\"timeout_express\":\"10m\","
            //        + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
            AlipayTradePagePayResponse alipayResponse = null;
            try {
                alipayResponse=alipayClient.pageExecute(alipayRequest);
                System.out.println(alipayResponse.getBody());//后台打印一下 支付宝支付的参数数据
                System.out.println(alipayResponse.getMsg());
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            response.setContentType("text/html;charset=UTF-8"); //设置编码
            response.getWriter().write(alipayResponse.getBody());  //将支付宝支付的首页显示给浏览器

            return   ;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }




    }

}
